package com.xul.crowd.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xul.crowd.constant.CrowdConstant;
import com.xul.crowd.entity.Role;
import com.xul.crowd.entity.RoleExample;
import com.xul.crowd.exception.AccessForbiddenException;
import com.xul.crowd.exception.LoginAcctAlreadyInUseException;
import com.xul.crowd.exception.RoleAcctAlreadyInUseException;
import com.xul.crowd.mapper.RoleMapper;
import com.xul.crowd.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author xul
 * @create 2021-07-24 14:02
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 权限查询 模糊带分页
     *
     * @param pageNum
     * @param pageSize
     * @param keyword
     * @return
     */
    @Override
    public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> roleList = roleMapper.selectRoleByKeyword(keyword);
        return new PageInfo<>(roleList);

    }

    /**
     * 添加角色role
     *
     * @param role
     */
    @Override
    public void saveRole(Role role) {
        try {
            roleMapper.insert(role);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                throw new RoleAcctAlreadyInUseException(CrowdConstant.MESSAGE_ROLE_USE);
            }
        }
    }

    /**
     * 更新角色role
     *
     * @param role
     */
    @Override
    public void update(Role role) {
        try {
            roleMapper.updateByPrimaryKey(role);
        } catch (Exception e) {
            throw new RoleAcctAlreadyInUseException(CrowdConstant.MESSAGE_ROLE_USE);
        }
    }

    /**
     * 批量删除角色 包含单个删除
     *
     * @param rodeIdList
     */
    @Override
    public void removeRole(List<Integer> rodeIdList) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        criteria.andIdIn(rodeIdList);
        roleMapper.deleteByExample(roleExample);
    }

    /**
     * 查询已经分配的角色
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getAssignRole(Integer adminId) {
        return roleMapper.selectAssignRole(adminId);
    }

    /**
     * 查询没有分配的角色
     * @param adminId
     * @return
     */
    @Override
    public List<Role> getUnAssignRole(Integer adminId) {
        return roleMapper.selectUnAssignRole(adminId);
    }
}
